package com.wpp.handler;

import com.wpp.protocol.RpcRequest;
import com.wpp.register.metric.ResponseTimeMetricHolder;
import com.wpp.register.metric.TimeMetric;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.util.StopWatch;

import java.time.LocalDateTime;
import java.util.concurrent.Callable;

/**
 * @author by wpp25
 * @Classname UserClientHandler
 * @Description
 * @Date 2020/11/25 21:13
 */
@ChannelHandler.Sharable
public class UserClientHandler extends ChannelInboundHandlerAdapter implements Callable {

    private RpcRequest rpcRequest;
    // 服务器返回数据
    private String result;
    // 事件处理上下文对象
    private ChannelHandlerContext channelHandlerContext;

    public void setRpcRequest(RpcRequest rpcRequest) {
        this.rpcRequest = rpcRequest;
    }

    /**
     * 客户端和服务器连接时 自动执行
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        this.channelHandlerContext = ctx;
    }

    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        result = msg.toString();
        notify();
    }

    @Override
    public synchronized Object call() throws Exception {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        channelHandlerContext.writeAndFlush(rpcRequest);
        wait();
        stopWatch.stop();


        System.out.printf("当前服务访问 消耗时间为: %s %n",stopWatch.getTotalTimeMillis());
        ResponseTimeMetricHolder.getInstance().resetResponseTime(rpcRequest,stopWatch);
        return result;
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        ctx.channel().closeFuture().sync();
        System.out.println("关闭连接。。。");
    }
}
